import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'
const cartStore = createSlice({
    name: 'cartStore',
    initialState: {
        menuList: [],
        foodList: [],
        currentMenu: '',
        cartList: [],
        totalCount: 0,
        deliveryCost: 5,
        startingFare: 20,
    },

    reducers: {
        fetchMenuList: (state, action) => {
            state.menuList = action.payload
        },
        fetchFoodList: (state, action) => {
            state.foodList = action.payload
        },
        setCurrentMenu: (state, action) => {
            state.currentMenu = action.payload
        },
        setCartList: (state, action) => {
            state.cartList = action.payload
        },
        setTotalCount: (state, action) => {
            state.totalCount = action.payload
        },
    },
})

const cartInfo = cartStore.reducer
const cartActions = cartStore.actions

const cartStoreFuns = {
    getMenuList: () => {
        return async dispatch => {
            const res = await axios.get('http://localhost:3004/getMenuList')
            console.log(res.data.value)
            dispatch(cartActions.fetchMenuList(res.data.value))
            dispatch(cartActions.setCurrentMenu(res.data.value[0].id))
        }
    },
    getCurrentMenuInfo: menuId => {
        return async dispatch => {
            const res = await axios.get(`http://localhost:3004/getMenuItems${menuId}`)
            dispatch(cartActions.fetchFoodList(res.data.value))
        }
    },
}

export { cartInfo, cartActions, cartStoreFuns }
